home *** CD-ROM | disk | FTP | other *** search
/ EuroCD 3 / EuroCD 3.iso / Programming / Python1.4_Source / Objects / stringobject.c < prev    next >
C/C++ Source or Header  |  1998-06-24  |  20KB  |  932 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* String object implementation */
  33.  
  34. #include "allobjects.h"
  35. #include "protos/stringobject_protos.h"
  36.  
  37. #include <ctype.h>
  38.  
  39. #ifdef COUNT_ALLOCS
  40. int null_strings, one_strings;
  41. #endif
  42.  
  43. #ifdef HAVE_LIMITS_H
  44. #include <limits.h>
  45. #else
  46. #ifndef UCHAR_MAX
  47. #define UCHAR_MAX 255
  48. #endif
  49. #endif
  50.  
  51. static stringobject *characters[UCHAR_MAX + 1];
  52. #ifndef DONT_SHARE_SHORT_STRINGS
  53. static stringobject *nullstring;
  54. #endif
  55.  
  56. /*
  57.    Newsizedstringobject() and newstringobject() try in certain cases
  58.    to share string objects.  When the size of the string is zero,
  59.    these routines always return a pointer to the same string object;
  60.    when the size is one, they return a pointer to an already existing
  61.    object if the contents of the string is known.  For
  62.    newstringobject() this is always the case, for
  63.    newsizedstringobject() this is the case when the first argument in
  64.    not NULL.
  65.    A common practice to allocate a string and then fill it in or
  66.    change it must be done carefully.  It is only allowed to change the
  67.    contents of the string if the obect was gotten from
  68.    newsizedstringobject() with a NULL first argument, because in the
  69.    future these routines may try to do even more sharing of objects.
  70. */
  71. object *
  72. newsizedstringobject(str, size)
  73.     char *str;
  74.     int size;
  75. {
  76.     register stringobject *op;
  77. #ifndef DONT_SHARE_SHORT_STRINGS
  78.     if (size == 0 && (op = nullstring) != NULL) {
  79. #ifdef COUNT_ALLOCS
  80.         null_strings++;
  81. #endif
  82.         INCREF(op);
  83.         return (object *)op;
  84.     }
  85.     if (size == 1 && str != NULL && (op = characters[*str & UCHAR_MAX]) != NULL) {
  86. #ifdef COUNT_ALLOCS
  87.         one_strings++;
  88. #endif
  89.         INCREF(op);
  90.         return (object *)op;
  91.     }
  92. #endif /* DONT_SHARE_SHORT_STRINGS */
  93.     op = (stringobject *)
  94.         malloc(sizeof(stringobject) + size * sizeof(char));
  95.     if (op == NULL)
  96.         return err_nomem();
  97.     op->ob_type = &Stringtype;
  98.     op->ob_size = size;
  99. #ifdef CACHE_HASH
  100.     op->ob_shash = -1;
  101. #endif
  102.     NEWREF(op);
  103.     if (str != NULL)
  104.         memcpy(op->ob_sval, str, size);
  105.     op->ob_sval[size] = '\0';
  106. #ifndef DONT_SHARE_SHORT_STRINGS
  107.     if (size == 0) {
  108.         nullstring = op;
  109.         INCREF(op);
  110.     } else if (size == 1 && str != NULL) {
  111.         characters[*str & UCHAR_MAX] = op;
  112.         INCREF(op);
  113.     }
  114. #endif
  115.     return (object *) op;
  116. }
  117.  
  118. object *
  119. newstringobject(str)
  120.     char *str;
  121. {
  122.     register unsigned int size = strlen(str);
  123.     register stringobject *op;
  124. #ifndef DONT_SHARE_SHORT_STRINGS
  125.     if (size == 0 && (op = nullstring) != NULL) {
  126. #ifdef COUNT_ALLOCS
  127.         null_strings++;
  128. #endif
  129.         INCREF(op);
  130.         return (object *)op;
  131.     }
  132.     if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) {
  133. #ifdef COUNT_ALLOCS
  134.         one_strings++;
  135. #endif
  136.         INCREF(op);
  137.         return (object *)op;
  138.     }
  139. #endif /* DONT_SHARE_SHORT_STRINGS */
  140.     op = (stringobject *)
  141.         malloc(sizeof(stringobject) + size * sizeof(char));
  142.     if (op == NULL)
  143.         return err_nomem();
  144.     op->ob_type = &Stringtype;
  145.     op->ob_size = size;
  146. #ifdef CACHE_HASH
  147.     op->ob_shash = -1;
  148. #endif
  149.     NEWREF(op);
  150.     strcpy(op->ob_sval, str);
  151. #ifndef DONT_SHARE_SHORT_STRINGS
  152.     if (size == 0) {
  153.         nullstring = op;
  154.         INCREF(op);
  155.     } else if (size == 1) {
  156.         characters[*str & UCHAR_MAX] = op;
  157.         INCREF(op);
  158.     }
  159. #endif
  160.     return (object *) op;
  161. }
  162.  
  163. static void
  164. string_dealloc(op)
  165.     object *op;
  166. {
  167.     DEL(op);
  168. }
  169.  
  170. int
  171. getstringsize(op)
  172.     register object *op;
  173. {
  174.     if (!is_stringobject(op)) {
  175.         err_badcall();
  176.         return -1;
  177.     }
  178.     return ((stringobject *)op) -> ob_size;
  179. }
  180.  
  181. /*const*/ char *
  182. getstringvalue(op)
  183.     register object *op;
  184. {
  185.     if (!is_stringobject(op)) {
  186.         err_badcall();
  187.         return NULL;
  188.     }
  189.     return ((stringobject *)op) -> ob_sval;
  190. }
  191.  
  192. /* Methods */
  193.  
  194. static int
  195. string_print(op, fp, flags)
  196.     stringobject *op;
  197.     FILE *fp;
  198.     int flags;
  199. {
  200.     int i;
  201.     char c;
  202.     int quote;
  203.     /* XXX Ought to check for interrupts when writing long strings */
  204.     if (flags & PRINT_RAW) {
  205.         fwrite(op->ob_sval, 1, (int) op->ob_size, fp);
  206.         return 0;
  207.     }
  208.  
  209.     /* figure out which quote to use; single is prefered */
  210.     quote = '\'';
  211.     if (strchr(op->ob_sval, '\'') && !strchr(op->ob_sval, '"'))
  212.         quote = '"';
  213.  
  214.     fputc(quote, fp);
  215.     for (i = 0; i < op->ob_size; i++) {
  216.         c = op->ob_sval[i];
  217.         if (c == quote || c == '\\')
  218.             fprintf(fp, "\\%c", c);
  219.         else if (c < ' ' || c >= 0177)
  220.             fprintf(fp, "\\%03o", c & 0377);
  221.         else
  222.             fputc(c, fp);
  223.     }
  224.     fputc(quote, fp);
  225.     return 0;
  226. }
  227.  
  228. static object *
  229. string_repr(op)
  230.     register stringobject *op;
  231. {
  232.     /* XXX overflow? */
  233.     int newsize = 2 + 4 * op->ob_size * sizeof(char);
  234.     object *v = newsizedstringobject((char *)NULL, newsize);
  235.     if (v == NULL) {
  236.         return NULL;
  237.     }
  238.     else {
  239.         register int i;
  240.         register char c;
  241.         register char *p;
  242.         int quote;
  243.  
  244.         /* figure out which quote to use; single is prefered */
  245.         quote = '\'';
  246.         if (strchr(op->ob_sval, '\'') && !strchr(op->ob_sval, '"'))
  247.             quote = '"';
  248.  
  249.         p = ((stringobject *)v)->ob_sval;
  250.         *p++ = quote;
  251.         for (i = 0; i < op->ob_size; i++) {
  252.             c = op->ob_sval[i];
  253.             if (c == quote || c == '\\')
  254.                 *p++ = '\\', *p++ = c;
  255.             else if (c < ' ' || c >= 0177) {
  256.                 sprintf(p, "\\%03o", c & 0377);
  257.                 while (*p != '\0')
  258.                     p++;
  259.             }
  260.             else
  261.                 *p++ = c;
  262.         }
  263.         *p++ = quote;
  264.         *p = '\0';
  265.         resizestring(&v, (int) (p - ((stringobject *)v)->ob_sval));
  266.         return v;
  267.     }
  268. }
  269.  
  270. static int
  271. string_length(a)
  272.     stringobject *a;
  273. {
  274.     return a->ob_size;
  275. }
  276.  
  277. static object *
  278. string_concat(a, bb)
  279.     register stringobject *a;
  280.     register object *bb;
  281. {
  282.     register unsigned int size;
  283.     register stringobject *op;
  284.     if (!is_stringobject(bb)) {
  285.         err_badarg();
  286.         return NULL;
  287.     }
  288. #define b ((stringobject *)bb)
  289.     /* Optimize cases with empty left or right operand */
  290.     if (a->ob_size == 0) {
  291.         INCREF(bb);
  292.         return bb;
  293.     }
  294.     if (b->ob_size == 0) {
  295.         INCREF(a);
  296.         return (object *)a;
  297.     }
  298.     size = a->ob_size + b->ob_size;
  299.     op = (stringobject *)
  300.         malloc(sizeof(stringobject) + size * sizeof(char));
  301.     if (op == NULL)
  302.         return err_nomem();
  303.     op->ob_type = &Stringtype;
  304.     op->ob_size = size;
  305. #ifdef CACHE_HASH
  306.     op->ob_shash = -1;
  307. #endif
  308.     NEWREF(op);
  309.     memcpy(op->ob_sval, a->ob_sval, (int) a->ob_size);
  310.     memcpy(op->ob_sval + a->ob_size, b->ob_sval, (int) b->ob_size);
  311.     op->ob_sval[size] = '\0';
  312.     return (object *) op;
  313. #undef b
  314. }
  315.  
  316. static object *
  317. string_repeat(a, n)
  318.     register stringobject *a;
  319.     register int n;
  320. {
  321.     register int i;
  322.     register unsigned int size;
  323.     register stringobject *op;
  324.     if (n < 0)
  325.         n = 0;
  326.     size = a->ob_size * n;
  327.     if (size == a->ob_size) {
  328.         INCREF(a);
  329.         return (object *)a;
  330.     }
  331.     op = (stringobject *)
  332.         malloc(sizeof(stringobject) + size * sizeof(char));
  333.     if (op == NULL)
  334.         return err_nomem();
  335.     op->ob_type = &Stringtype;
  336.     op->ob_size = size;
  337. #ifdef CACHE_HASH
  338.     op->ob_shash = -1;
  339. #endif
  340.     NEWREF(op);
  341.     for (i = 0; i < size; i += a->ob_size)
  342.         memcpy(op->ob_sval+i, a->ob_sval, (int) a->ob_size);
  343.     op->ob_sval[size] = '\0';
  344.     return (object *) op;
  345. }
  346.  
  347. /* String slice a[i:j] consists of characters a[i] ... a[j-1] */
  348.  
  349. static object *
  350. string_slice(a, i, j)
  351.     register stringobject *a;
  352.     register int i, j; /* May be negative! */
  353. {
  354.     if (i < 0)
  355.         i = 0;
  356.     if (j < 0)
  357.         j = 0; /* Avoid signed/unsigned bug in next line */
  358.     if (j > a->ob_size)
  359.         j = a->ob_size;
  360.     if (i == 0 && j == a->ob_size) { /* It's the same as a */
  361.         INCREF(a);
  362.         return (object *)a;
  363.     }
  364.     if (j < i)
  365.         j = i;
  366.     return newsizedstringobject(a->ob_sval + i, (int) (j-i));
  367. }
  368.  
  369. static object *
  370. string_item(a, i)
  371.     stringobject *a;
  372.     register int i;
  373. {
  374.     int c;
  375.     object *v;
  376.     if (i < 0 || i >= a->ob_size) {
  377.         err_setstr(IndexError, "string index out of range");
  378.         return NULL;
  379.     }
  380.     c = a->ob_sval[i] & UCHAR_MAX;
  381.     v = (object *) characters[c];
  382. #ifdef COUNT_ALLOCS
  383.     if (v != NULL)
  384.         one_strings++;
  385. #endif
  386.     if (v == NULL) {
  387.         v = newsizedstringobject((char *)NULL, 1);
  388.         if (v == NULL)
  389.             return NULL;
  390.         characters[c] = (stringobject *) v;
  391.         ((stringobject *)v)->ob_sval[0] = c;
  392.     }
  393.     INCREF(v);
  394.     return v;
  395. }
  396.  
  397. static int
  398. string_compare(a, b)
  399.     stringobject *a, *b;
  400. {
  401.     int len_a = a->ob_size, len_b = b->ob_size;
  402.     int min_len = (len_a < len_b) ? len_a : len_b;
  403.     int cmp;
  404.     if (min_len > 0) {
  405.         cmp = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval);
  406.         if (cmp == 0)
  407.             cmp = memcmp(a->ob_sval, b->ob_sval, min_len);
  408.         if (cmp != 0)
  409.             return cmp;
  410.     }
  411.     return (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0;
  412. }
  413.  
  414. static long
  415. string_hash(a)
  416.     stringobject *a;
  417. {
  418.     register int len;
  419.     register unsigned char *p;
  420.     register long x;
  421.  
  422. #ifdef CACHE_HASH
  423.     if (a->ob_shash != -1)
  424.         return a->ob_shash;
  425. #endif
  426.     len = a->ob_size;
  427.     p = (unsigned char *) a->ob_sval;
  428.     x = *p << 7;
  429.     while (--len >= 0)
  430.         x = (1000003*x) ^ *p++;
  431.     x ^= a->ob_size;
  432.     if (x == -1)
  433.         x = -2;
  434. #ifdef CACHE_HASH
  435.     a->ob_shash = x;
  436. #endif
  437.     return x;
  438. }
  439.  
  440. static sequence_methods string_as_sequence = {
  441.     (inquiry)string_length, /*sq_length*/
  442.     (binaryfunc)string_concat, /*sq_concat*/
  443.     (intargfunc)string_repeat, /*sq_repeat*/
  444.     (intargfunc)string_item, /*sq_item*/
  445.     (intintargfunc)string_slice, /*sq_slice*/
  446.     0,        /*sq_ass_item*/
  447.     0,        /*sq_ass_slice*/
  448. };
  449.  
  450. typeobject Stringtype = {
  451.     OB_HEAD_INIT(&Typetype)
  452.     0,
  453.     "string",
  454.     sizeof(stringobject),
  455.     sizeof(char),
  456.     (destructor)string_dealloc, /*tp_dealloc*/
  457.     (printfunc)string_print, /*tp_print*/
  458.     0,        /*tp_getattr*/
  459.     0,        /*tp_setattr*/
  460.     (cmpfunc)string_compare, /*tp_compare*/
  461.     (reprfunc)string_repr, /*tp_repr*/
  462.     0,        /*tp_as_number*/
  463.     &string_as_sequence,    /*tp_as_sequence*/
  464.     0,        /*tp_as_mapping*/
  465.     (hashfunc)string_hash, /*tp_hash*/
  466. };
  467.  
  468. void
  469. joinstring(pv, w)
  470.     register object **pv;
  471.     register object *w;
  472. {
  473.     register object *v;
  474.     if (*pv == NULL)
  475.         return;
  476.     if (w == NULL || !is_stringobject(*pv)) {
  477.         DECREF(*pv);
  478.         *pv = NULL;
  479.         return;
  480.     }
  481.     v = string_concat((stringobject *) *pv, w);
  482.     DECREF(*pv);
  483.     *pv = v;
  484. }
  485.  
  486. void
  487. joinstring_decref(pv, w)
  488.     register object **pv;
  489.     register object *w;
  490. {
  491.     joinstring(pv, w);
  492.     XDECREF(w);
  493. }
  494.  
  495.  
  496. /* The following function breaks the notion that strings are immutable:
  497.    it changes the size of a string.  We get away with this only if there
  498.    is only one module referencing the object.  You can also think of it
  499.    as creating a new string object and destroying the old one, only
  500.    more efficiently.  In any case, don't use this if the string may
  501.    already be known to some other part of the code... */
  502.  
  503. int
  504. resizestring(pv, newsize)
  505.     object **pv;
  506.     int newsize;
  507. {
  508.     register object *v;
  509.     register stringobject *sv;
  510.     v = *pv;
  511.     if (!is_stringobject(v) || v->ob_refcnt != 1) {
  512.         *pv = 0;
  513.         DECREF(v);
  514.         err_badcall();
  515.         return -1;
  516.     }
  517.     /* XXX UNREF/NEWREF interface should be more symmetrical */
  518. #ifdef Py_REF_DEBUG
  519.     --_Py_RefTotal;
  520. #endif
  521.     UNREF(v);
  522.     *pv = (object *)
  523.         realloc((char *)v,
  524.             sizeof(stringobject) + newsize * sizeof(char));
  525.     if (*pv == NULL) {
  526.         DEL(v);
  527.         err_nomem();
  528.         return -1;
  529.     }
  530.     NEWREF(*pv);
  531.     sv = (stringobject *) *pv;
  532.     sv->ob_size = newsize;
  533.     sv->ob_sval[newsize] = '\0';
  534.     return 0;
  535. }
  536.  
  537. /* Helpers for formatstring */
  538.  
  539. static object *
  540. getnextarg(args, arglen, p_argidx)
  541.     object *args;
  542.     int arglen;
  543.     int *p_argidx;
  544. {
  545.     int argidx = *p_argidx;
  546.     if (argidx < arglen) {
  547.         (*p_argidx)++;
  548.         if (arglen < 0)
  549.             return args;
  550.         else
  551.             return gettupleitem(args, argidx);
  552.     }
  553.     err_setstr(TypeError, "not enough arguments for format string");
  554.     return NULL;
  555. }
  556.  
  557. #define F_LJUST (1<<0)
  558. #define F_SIGN    (1<<1)
  559. #define F_BLANK (1<<2)
  560. #define F_ALT    (1<<3)
  561. #define F_ZERO    (1<<4)
  562.  
  563. extern double fabs PROTO((double));
  564.  
  565. static char *
  566. formatfloat(flags, prec, type, v)
  567.     int flags;
  568.     int prec;
  569.     int type;
  570.     object *v;
  571. {
  572.     char fmt[20];
  573.     static char buf[120];
  574.     double x;
  575.     if (!getargs(v, "d;float argument required", &x))
  576.         return NULL;
  577.     if (prec < 0)
  578.         prec = 6;
  579.     if (prec > 50)
  580.         prec = 50; /* Arbitrary limitation */
  581.     if (type == 'f' && fabs(x)/1e25 >= 1e25)
  582.         type = 'g';
  583.     sprintf(fmt, "%%%s.%d%c", (flags&F_ALT) ? "#" : "", prec, type);
  584.     sprintf(buf, fmt, x);
  585.     return buf;
  586. }
  587.  
  588. static char *
  589. formatint(flags, prec, type, v)
  590.     int flags;
  591.     int prec;
  592.     int type;
  593.     object *v;
  594. {
  595.     char fmt[20];
  596.     static char buf[50];
  597.     long x;
  598.     if (!getargs(v, "l;int argument required", &x))
  599.         return NULL;
  600.     if (prec < 0)
  601.         prec = 1;
  602.     sprintf(fmt, "%%%s.%dl%c", (flags&F_ALT) ? "#" : "", prec, type);
  603.     sprintf(buf, fmt, x);
  604.     return buf;
  605. }
  606.  
  607. static char *
  608. formatchar(v)
  609.     object *v;
  610. {
  611.     static char buf[2];
  612.     if (is_stringobject(v)) {
  613.         if (!getargs(v, "c;%c requires int or char", &buf[0]))
  614.             return NULL;
  615.     }
  616.     else {
  617.         if (!getargs(v, "b;%c requires int or char", &buf[0]))
  618.             return NULL;
  619.     }
  620.     buf[1] = '\0';
  621.     return buf;
  622. }
  623.  
  624.  
  625. /* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...) */
  626.  
  627. object *
  628. formatstring(format, args)
  629.     object *format;
  630.     object *args;
  631. {
  632.     char *fmt, *res;
  633.     int fmtcnt, rescnt, reslen, arglen, argidx;
  634.     int args_owned = 0;
  635.     object *result;
  636.     object *dict = NULL;
  637.     if (format == NULL || !is_stringobject(format) || args == NULL) {
  638.         err_badcall();
  639.         return NULL;
  640.     }
  641.     fmt = getstringvalue(format);
  642.     fmtcnt = getstringsize(format);
  643.     reslen = rescnt = fmtcnt + 100;
  644.     result = newsizedstringobject((char *)NULL, reslen);
  645.     if (result == NULL)
  646.         return NULL;
  647.     res = getstringvalue(result);
  648.     if (is_tupleobject(args)) {
  649.         arglen = gettuplesize(args);
  650.         argidx = 0;
  651.     }
  652.     else {
  653.         arglen = -1;
  654.         argidx = -2;
  655.     }
  656.     if (args->ob_type->tp_as_mapping)
  657.         dict = args;
  658.     while (--fmtcnt >= 0) {
  659.         if (*fmt != '%') {
  660.             if (--rescnt < 0) {
  661.                 rescnt = fmtcnt + 100;
  662.                 reslen += rescnt;
  663.                 if (resizestring(&result, reslen) < 0)
  664.                     return NULL;
  665.                 res = getstringvalue(result) + reslen - rescnt;
  666.                 --rescnt;
  667.             }
  668.             *res++ = *fmt++;
  669.         }
  670.         else {
  671.             /* Got a format specifier */
  672.             int flags = 0;
  673.             char *fmtstart = fmt++;
  674.             int width = -1;
  675.             int prec = -1;
  676.             int size = 0;
  677.             int c = '\0';
  678.             int fill;
  679.             object *v;
  680.             object *temp = NULL;
  681.             char *buf;
  682.             int sign;
  683.             int len;
  684.             if (*fmt == '(') {
  685.                 char *keystart;
  686.                 int keylen;
  687.                 object *key;
  688.  
  689.                 if (dict == NULL) {
  690.                     err_setstr(TypeError,
  691.                          "format requires a mapping"); 
  692.                     goto error;
  693.                 }
  694.                 ++fmt;
  695.                 --fmtcnt;
  696.                 keystart = fmt;
  697.                 while (--fmtcnt >= 0 && *fmt != ')')
  698.                     fmt++;
  699.                 keylen = fmt - keystart;
  700.                 ++fmt;
  701.                 if (fmtcnt < 0) {
  702.                     err_setstr(ValueError,
  703.                            "incomplete format key");
  704.                     goto error;
  705.                 }
  706.                 key = newsizedstringobject(keystart, keylen);
  707.                 if (key == NULL)
  708.                     goto error;
  709.                 if (args_owned) {
  710.                     DECREF(args);
  711.                     args_owned = 0;
  712.                 }
  713.                 args = PyObject_GetItem(dict, key);
  714.                 DECREF(key);
  715.                 if (args == NULL) {
  716.                     goto error;
  717.                 }
  718.                 args_owned = 1;
  719.                 arglen = -1;
  720.                 argidx = -2;
  721.             }
  722.             while (--fmtcnt >= 0) {
  723.                 switch (c = *fmt++) {
  724.                 case '-': flags |= F_LJUST; continue;
  725.                 case '+': flags |= F_SIGN; continue;
  726.                 case ' ': flags |= F_BLANK; continue;
  727.                 case '#': flags |= F_ALT; continue;
  728.                 case '0': flags |= F_ZERO; continue;
  729.                 }
  730.                 break;
  731.             }
  732.             if (c == '*') {
  733.                 v = getnextarg(args, arglen, &argidx);
  734.                 if (v == NULL)
  735.                     goto error;
  736.                 if (!is_intobject(v)) {
  737.                     err_setstr(TypeError, "* wants int");
  738.                     goto error;
  739.                 }
  740.                 width = getintvalue(v);
  741.                 if (width < 0)
  742.                     width = 0;
  743.                 if (--fmtcnt >= 0)
  744.                     c = *fmt++;
  745.             }
  746.             else if (c >= 0 && isdigit(c)) {
  747.                 width = c - '0';
  748.                 while (--fmtcnt >= 0) {
  749.                     c = Py_CHARMASK(*fmt++);
  750.                     if (!isdigit(c))
  751.                         break;
  752.                     if ((width*10) / 10 != width) {
  753.                         err_setstr(ValueError,
  754.                                "width too big");
  755.                         goto error;
  756.                     }
  757.                     width = width*10 + (c - '0');
  758.                 }
  759.             }
  760.             if (c == '.') {
  761.                 prec = 0;
  762.                 if (--fmtcnt >= 0)
  763.                     c = *fmt++;
  764.                 if (c == '*') {
  765.                     v = getnextarg(args, arglen, &argidx);
  766.                     if (v == NULL)
  767.                         goto error;
  768.                     if (!is_intobject(v)) {
  769.                         err_setstr(TypeError,
  770.                                "* wants int");
  771.                         goto error;
  772.                     }
  773.                     prec = getintvalue(v);
  774.                     if (prec < 0)
  775.                         prec = 0;
  776.                     if (--fmtcnt >= 0)
  777.                         c = *fmt++;
  778.                 }
  779.                 else if (c >= 0 && isdigit(c)) {
  780.                     prec = c - '0';
  781.                     while (--fmtcnt >= 0) {
  782.                         c = Py_CHARMASK(*fmt++);
  783.                         if (!isdigit(c))
  784.                             break;
  785.                         if ((prec*10) / 10 != prec) {
  786.                             err_setstr(ValueError,
  787.                                 "prec too big");
  788.                             goto error;
  789.                         }
  790.                         prec = prec*10 + (c - '0');
  791.                     }
  792.                 }
  793.             } /* prec */
  794.             if (fmtcnt >= 0) {
  795.                 if (c == 'h' || c == 'l' || c == 'L') {
  796.                     size = c;
  797.                     if (--fmtcnt >= 0)
  798.                         c = *fmt++;
  799.                 }
  800.             }
  801.             if (fmtcnt < 0) {
  802.                 err_setstr(ValueError, "incomplete format");
  803.                 goto error;
  804.             }
  805.             if (c != '%') {
  806.                 v = getnextarg(args, arglen, &argidx);
  807.                 if (v == NULL)
  808.                     goto error;
  809.             }
  810.             sign = 0;
  811.             fill = ' ';
  812.             switch (c) {
  813.             case '%':
  814.                 buf = "%";
  815.                 len = 1;
  816.                 break;
  817.             case 's':
  818.                 temp = strobject(v);
  819.                 if (temp == NULL)
  820.                     goto error;
  821.                 buf = getstringvalue(temp);
  822.                 len = getstringsize(temp);
  823.                 if (prec >= 0 && len > prec)
  824.                     len = prec;
  825.                 break;
  826.             case 'i':
  827.             case 'd':
  828.             case 'u':
  829.             case 'o':
  830.             case 'x':
  831.             case 'X':
  832.                 if (c == 'i')
  833.                     c = 'd';
  834.                 buf = formatint(flags, prec, c, v);
  835.                 if (buf == NULL)
  836.                     goto error;
  837.                 len = strlen(buf);
  838.                 sign = (c == 'd');
  839.                 if (flags&F_ZERO)
  840.                     fill = '0';
  841.                 break;
  842.             case 'e':
  843.             case 'E':
  844.             case 'f':
  845.             case 'g':
  846.             case 'G':
  847.                 buf = formatfloat(flags, prec, c, v);
  848.                 if (buf == NULL)
  849.                     goto error;
  850.                 len = strlen(buf);
  851.                 sign = 1;
  852.                 if (flags&F_ZERO)
  853.                     fill = '0';
  854.                 break;
  855.             case 'c':
  856.                 buf = formatchar(v);
  857.                 if (buf == NULL)
  858.                     goto error;
  859.                 len = 1;
  860.                 break;
  861.             default:
  862.                 err_setstr(ValueError,
  863.                        "unsupported format character");
  864.                 goto error;
  865.             }
  866.             if (sign) {
  867.                 if (*buf == '-' || *buf == '+') {
  868.                     sign = *buf++;
  869.                     len--;
  870.                 }
  871.                 else if (flags & F_SIGN)
  872.                     sign = '+';
  873.                 else if (flags & F_BLANK)
  874.                     sign = ' ';
  875.                 else
  876.                     sign = '\0';
  877.             }
  878.             if (width < len)
  879.                 width = len;
  880.             if (rescnt < width + (sign != '\0')) {
  881.                 reslen -= rescnt;
  882.                 rescnt = width + fmtcnt + 100;
  883.                 reslen += rescnt;
  884.                 if (resizestring(&result, reslen) < 0)
  885.                     return NULL;
  886.                 res = getstringvalue(result) + reslen - rescnt;
  887.             }
  888.             if (sign) {
  889.                 if (fill != ' ')
  890.                     *res++ = sign;
  891.                 rescnt--;
  892.                 if (width > len)
  893.                     width--;
  894.             }
  895.             if (width > len && !(flags&F_LJUST)) {
  896.                 do {
  897.                     --rescnt;
  898.                     *res++ = fill;
  899.                 } while (--width > len);
  900.             }
  901.             if (sign && fill == ' ')
  902.                 *res++ = sign;
  903.             memcpy(res, buf, len);
  904.             res += len;
  905.             rescnt -= len;
  906.             while (--width >= len) {
  907.                 --rescnt;
  908.                 *res++ = ' ';
  909.             }
  910.                         if (dict && (argidx < arglen) && c != '%') {
  911.                                 err_setstr(TypeError,
  912.                                            "not all arguments converted");
  913.                                 goto error;
  914.                         }
  915.             XDECREF(temp);
  916.         } /* '%' */
  917.     } /* until end */
  918.     if (argidx < arglen && !dict) {
  919.         err_setstr(TypeError, "not all arguments converted");
  920.         goto error;
  921.     }
  922.     if (args_owned)
  923.         DECREF(args);
  924.     resizestring(&result, reslen - rescnt);
  925.     return result;
  926.  error:
  927.     DECREF(result);
  928.     if (args_owned)
  929.         DECREF(args);
  930.     return NULL;
  931. }
  932.